<template>
  <div class="app-container">
    <!-- 表格-条件筛区域  -->
    <div class="filter-container">
      <el-input v-model="searchParam.SEARCH_LIKE_rolename" placeholder="请输入关键字" style="width: 200px;" class="filter-item" @keyup.enter.native="handleFilter" />
      <el-button v-waves class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">搜索</el-button>
      <el-button class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-edit" @click="handleCreate">添加</el-button>
    </div>

    <!-- 表格-内容区域 -->
    <el-table :key="tableKey" v-loading="listLoading" :data="tableList" border fit highlight-current-row style="width: 100%;">
      <el-table-column label="序号" prop="id" align="center" width="270px">
        <template slot-scope="scope">
          <span>{{ scope.row.id }}</span>
        </template>
      </el-table-column>
      <el-table-column label="角色名称" min-width="60px" align="center">
        <template slot-scope="scope">
          <span class="link-type" @click="handleUpdate(scope.row)">{{ scope.row.roleName }}</span>
        </template>
      </el-table-column>
      <el-table-column label="角色编码" min-width="60px" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.roleCode }}</span>
        </template>
      </el-table-column>
      <el-table-column label="角色描述" min-width="100px" align="left">
        <template slot-scope="scope">
          <span>{{ scope.row.remark }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="200" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button type="primary" @click="handleUpdate(scope.row)">编辑</el-button>
          <el-button type="danger" @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 表格-页脚区域 -->
    <pagination v-show="tableTotal>0" :total="tableTotal" :page.sync="pageRequest.pageNum" :limit.sync="pageRequest.pageSize" @pagination="getList" />

    <!--新增编辑界面-->
    <el-dialog :title="operation?'新增':'编辑'" width="50%" top="5vh" :visible.sync="dialogFormVisible" :close-on-click-modal="false">
      <div style="height:500px;overflow-y: scroll;">
        <el-form ref="dataForm" :model="dataForm" label-width="100px" :rules="dataFormRules">
          <el-form-item label="角色名称" prop="roleName">
            <el-input v-model="dataForm.roleName" size="mini" auto-complete="off" />
          </el-form-item>
          <el-form-item label="角色编码" prop="roleCode">
            <el-input v-model="dataForm.roleCode" size="mini" auto-complete="off" />
          </el-form-item>
          <el-form-item label="角色描述" prop="remark">
            <el-input v-model="dataForm.remark" size="mini" auto-complete="off" />
          </el-form-item>
          <el-form-item label="权限配置" prop="remark">
            <el-tree ref="tree" size="mini" style="margin-top:10px" :data="data" show-checkbox default-expand-all node-key="id" :props="defaultProps" />
          </el-form-item>
        </el-form>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button size="mini" @click.native="closeDialog()">取消</el-button>
        <el-button size="mini" :loading="editLoading" type="primary" @click.native="saveFormData()">提交</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>

import waves from '@/directive/waves' // Waves directive
import Pagination from '@/components/Pagination' // Secondary package based on el-pagination
import { getMenuTreeList, getRoleList, saveRoleInfo, getRoleCheckedIds, deleteRole } from '../../../api/modules/cm-system'

export default {
  name: 'SystemRole',
  components: { Pagination },
  directives: { waves },
  filters: { },
  data() {
    return {
      tableKey: 0,
      tableList: [], // 表格数据源
      tableTotal: 0, // 表格总条数数据
      listLoading: true,
      pageRequest: { pageNum: 1, pageSize: 10 },
      searchParam: { SEARCH_LIKE_rolename: '' },
      // 默认不显示弹出框
      dialogFormVisible: false,
      operation: true, // true:新增, false:编辑
      editLoading: false, // 保存表单时loading框
      data: [], // 角色权限---树形结构渲染
      checkedIds: [],
      // 树形结构---默认属性值设置
      defaultProps: {
        children: 'children',
        label: 'name'
      },
      // 新增编辑界面数据
      dataForm: {},
      initDataForm: { roleName: '', roleCode: '', remark: '' },
      // 表单检验规则
      dataFormRules: {
        roleName: [{ required: true, message: '请输入角色名', trigger: 'blur' }],
        roleCode: [{ required: true, message: '请输入角色编码', trigger: 'blur' }]
      }
    }
  },
  created() {
    this.getList()
    this.getMenuData()
  },
  methods: {
    // 获取菜单树信息---
    getMenuData: function() {
      // 【API请求】----获取菜单树列表
      getMenuTreeList().then((res) => {
        this.data = res.result
      }).catch((res) => {
      })
    },
    // 获取表格数据
    getList() {
      this.listLoading = true
      // 【API请求】----获取角色列表数据
      getRoleList(this.pageRequest).then(response => {
          // console.log(response)
          this.tableList = response.result.content
          this.tableTotal = response.result.total
          this.listLoading = false
      })
    },
    // 表格数据筛选
    handleFilter() {
      this.pageRequest.searchParam = this.searchParam
      this.getList()
    },

    // 【按钮点击】--- 弹出新增表单
    handleCreate() {
      this.operation = true
      this.dataForm = this.initDataForm
      this.dialogFormVisible = true
      this.checkedIds = []
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
        this.$refs.tree.setCheckedKeys([])
        // this.$refs.tree.setChecked ( value , true , false   );
        this.editLoading = false
      })
    },
    // 【按钮点击】--- 弹出编辑表单
    handleUpdate(row) {
      this.operation = false
      this.dataForm = Object.assign({}, row)
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
        this.editLoading = false
        this.$refs.tree.setCheckedKeys([])
        // 【API请求】--- 获取角色信息绑定的菜单资源
        getRoleCheckedIds({ roleId: row.id }).then(response => {
            this.checkedIds = response.result
          // this.$refs.tree.setCheckedKeys(this.checkedIds  );
          const that = this
          setTimeout(() => {
              response.result.forEach(value => {
                  this.$refs.tree.setChecked(value, true, false)
              })
          }, 100)
        })
      })
    },
    // 保存表单数据
    saveFormData() {
      this.$refs['dataForm'].validate((valid) => {
        if (!valid) {
          return false
        }
        this.editLoading = true
        const roleMenus0 = this.$refs.tree.getCheckedKeys()
        // let roleMenus1 = [];
        const roleMenus1 = this.$refs.tree.getHalfCheckedKeys()
        const roleMenus = roleMenus0.concat(roleMenus1)
        // 封装请求实体类
        const submitEntity = this.dataForm
        submitEntity.menuIds = JSON.stringify(roleMenus)
        // 【API请求】----保存角色数据
        saveRoleInfo(submitEntity).then(() => {
          this.editLoading = false// 关闭loading框
          this.dialogFormVisible = false// 关闭表单页面
          this.$refs['dataForm'].resetFields()// 重置表单数据
          this.getList()// 重新获取表格数据
          this.$notify({ title: '成功', message: '保存成功', type: 'success', duration: 2000 })
        })
      })
    },
    // 【按钮点击】---删除行
    handleDelete(row) {
      this.$confirm('确认删除该记录吗？', '提示', {}).then(() => {
        // 【API请求】---- 删除角色数据
        deleteRole({ ids: row.id }).then(() => {
          this.$message({ message: '操作成功', type: 'success' })
          this.getList()
        })
      }).catch(() => {
      })
    },
    // 关闭表单弹出框
    closeDialog() {
      this.$refs['dataForm'].resetFields()
      this.dialogFormVisible = false
    }

  }
}
</script>
